import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:live_bg_mobile/common/const/app_color_const.dart';
import 'package:live_bg_mobile/widget/ripple_container.dart';

import '../common/api/staff_api.dart';
import '../common/const/app_style_const.dart';
import '../common/type/user_picker_type.dart';
import '../common/util/common_util.dart';

class UserPicker extends StatefulWidget {
  final Map? queryParams;
  final EdgeInsets contentPadding;
  final double headerHeight;
  final double bodyHeight;
  final void Function(UserPickerType result) onResult;
  final bool Function(UserPickerType result) onChecked;
  final void Function()? onCancel;

  final Widget Function(BuildContext context, dynamic user, TextStyle style)?
      labelBuilder;

  const UserPicker({
    key,
    required this.onResult,
    required this.onChecked,
    this.onCancel,
    this.bodyHeight = 200.0,
    this.headerHeight = 50.0,
    this.contentPadding =
        const EdgeInsets.only(left: 6.0, right: 6.0, top: 10.0, bottom: 10.0),
    this.queryParams,
    this.labelBuilder,
  }) : super(key: key);

  @override
  UserPickerState createState() => UserPickerState();
}

class UserPickerState extends State<UserPicker> {
  List<dynamic> userList = [];
  int userIndex = -1;
  bool userListLoading = false;

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    initData();
  }

  initData() {
    setState(() {
      userListLoading = true;
    });

    StaffApi.getStaffList(widget.queryParams ?? {}).then((res) {
      if (null != res.data && res.data["isSuccess"]) {
        userList = res.data["data"];
        userListLoading = false;
        setState(() {});
      } else {
        userList = [];
        userListLoading = false;
        setState(() {});
        CommonUtil.showToast(res.data["msg"]);
      }
    });
  }

  getResultData() {
    UserPickerType userPickerType = UserPickerType();
    userPickerType.id = userList[userIndex]["id"] ?? 0;
    userPickerType.employeeNum = userList[userIndex]["employeeNum"] ?? "";
    userPickerType.userName = userList[userIndex]["userName"] ?? "";
    userPickerType.hasAdminRole = userList[userIndex]["hasAdminRole"] ?? false;
    userPickerType.tel = userList[userIndex]["tel"] ?? "";

    return userPickerType;
  }

  Widget listViewItem(
      dynamic user, TextStyle labelStyle, GestureTapCallback onTop) {
    return RippleContainer(
      onTap: onTop,
      child: Container(
        alignment: Alignment.centerLeft,
        padding: widget.contentPadding,
        child: null != widget.labelBuilder
            ? widget.labelBuilder!(context, user, labelStyle)
            : Text(user['userName'], style: labelStyle),
      ),
    );
  }

  Widget userListWidget() {
    if (userListLoading) {
      return Container(
        decoration: const BoxDecoration(
          color: whiteColor,
        ),
        child: const Center(
          child: CupertinoActivityIndicator(
            animating: true,
          ),
        ),
      );
    }

    return Container(
        decoration: const BoxDecoration(
          color: whiteColor,
        ),
        child: ListView.builder(
            itemCount: userList.length,
            itemBuilder: (BuildContext context, int index) {
              return listViewItem(userList[index],
                  (userIndex == index ? itemActiveStyle : itemStyle), () {
                userIndex = index;
                setState(() {});
              });
            }));
  }

  Widget headerWidget() {
    return Container(
      height: widget.headerHeight,
      decoration: const BoxDecoration(
        color: whiteColor,
        border: Border(bottom: borderStyle),
      ),
      child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            TextButton(
              style: cancelBtnStyle,
              child: const Text('取消'),
              onPressed: () {
                if (null != widget.onCancel) {
                  widget.onCancel!();
                }
                Navigator.pop(context);
              },
            ),
            TextButton(
              child: const Text('确定'),
              onPressed: () {
                UserPickerType result = getResultData();
                if (widget.onChecked(result)) {
                  widget.onResult(result);
                  Navigator.pop(context);
                }
              },
            ),
          ]),
    );
  }

  Widget bodyWidget() {
    return SizedBox(
      height: widget.bodyHeight,
      child: Row(
        children: <Widget>[Expanded(child: userListWidget())],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        headerWidget(),
        bodyWidget(),
      ],
    );
  }
}
